package com.suning.sawp.service.impl.yjhx;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.google.common.base.Charsets;
import com.suning.rsc.dto.responsedto.MbfResponse;
import com.suning.rsc.httpservice.annotation.EsbEIHttpWired;
import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.esb.AccountActiveQueryReq;
import com.suning.sawp.dto.esb.AccountActiveQueryResp;
import com.suning.sawp.dto.esb.LocateMemberInfo;
import com.suning.sawp.intf.esb.EppAccountActiveStatusEsbService;
import com.suning.sawp.intf.esb.MemberInfoService;
import com.suning.sawp.intf.yjhx.OldForNewService;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.MD5Util;
import com.suning.sawp.service.util.SCMConfigUtil;
import com.suning.sawp.service.util.XmlUtils;

/**
 * 以旧换新服务
 *
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class OldForNewServiceImpl implements OldForNewService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(OldForNewServiceImpl.class);

    /**
     * 易付宝校验开关
     */
    private static final String SWITCH_ON = "1";
    
    /**
     * 易付宝账户是否激活接口
     */
    EppAccountActiveStatusEsbService esbService;

    /**
     * 查询易购会员信息服务
     */
    @Autowired
    MemberInfoService memberInfoService;

    @EsbEIHttpWired
    public void setEppAccountActiveStatusEsbService(EppAccountActiveStatusEsbService esbService) {
        this.esbService = esbService;
    }

    /**
     * 获取以旧换新首页地址
     */
    @Override
    public ReturnMsg<String> getIndexUrl(String mobileNo, String empNo, String storeCode) {
        LOGGER.info("getIndexUrl enter, mobileNo={},empNo={},storeCode={}",
                new Object[] { mobileNo, empNo, storeCode });
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        // 根据手机号查询易购会员信息
        LocateMemberInfo localMember = memberInfoService.locateMemberByMobileNo(mobileNo);
        if (!validEppSwitch()) {
            // 开关关闭
            if (null != localMember && StringUtils.isNotBlank(localMember.getCustNum())) {
                // 是易购会员
                // 取以旧换新URL地址
                String url = getUrl(localMember.getCustNum(), empNo, storeCode);
                // 地址不为空时,返回成功
                if (StringUtils.isNotBlank(url)) {
                    returnMsg.setData(url);
                } else {
                    // 配置信息不完善
                    returnMsg.setError(ErrorCodeConstants.ERR_0030);
                }
            } else {
                returnMsg.setError(ErrorCodeConstants.ERR_0056);
            }
            
            return returnMsg;
        }
        // 是易购会员
        if (null != localMember && StringUtils.isNotBlank(localMember.getCustNum())) {
            // 判断客户是否绑定易付宝
            AccountActiveQueryResp activeInfo = isActive(localMember.getCustNum());
            // 参数异常
            if (null == activeInfo) {
                returnMsg.setError(ErrorCodeConstants.ERR_0029);
            } else if (activeInfo.isBinding()) {
                // 绑定易付宝,已激活
                if (activeInfo.isActive()) {
                    // 取以旧换新URL地址
                    String url = getUrl(localMember.getCustNum(), empNo, storeCode);
                    // 地址不为空时,返回成功
                    if (StringUtils.isNotBlank(url)) {
                        returnMsg.setData(url);
                    } else {
                        // 配置信息不完善
                        returnMsg.setError(ErrorCodeConstants.ERR_0030);
                    }
                } else {
                    // 绑定易付宝,未激活状态
                    returnMsg.setError(ErrorCodeConstants.ERR_0031);
                }
            } else {
                // 未绑定易付宝
                returnMsg.setError(ErrorCodeConstants.ERR_0032);
            }
        } else {
            // 手机号没有注册苏宁易购会员
            returnMsg.setError(ErrorCodeConstants.ERR_0033);
        }
        LOGGER.info("getIndexUrl exit, mobileNo={},empNo={},storeCode={}", new Object[] { mobileNo, empNo, storeCode });
        return returnMsg;
    }
    
    /**
     * 
     * 功能描述: 以旧换新易付宝校验开关<br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean validEppSwitch() {
        if (SWITCH_ON.equals(SCMConfigUtil.getConfig(ConfigConstants.YJHX_VALID_EPP_SWITCH))) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 拼接以旧换新首页地址
     *
     * @param custNo
     * @param empNo
     * @param storeCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getUrl(String custNo, String empNo, String storeCode) {
        //prd:http://hx.m.suning.com/wap/xx/index.do?custNo=$custNo$&promotionUser=$promotionUser$&sourceShopCode=$sourceShopCode$&reqTime=$reqTime$&authCode=$authCode$,
        // 查询以旧换新首页地址
        String url = SCMConfigUtil.getConfig("oldForNewIndex");
        // 查询加密key值
        String authCodeKey = SCMConfigUtil.getConfig("oldForNewAuthCodeKey");
        // 同时不为空时,组装URL地址
        if (StringUtils.isNotBlank(url) && StringUtils.isNotBlank(authCodeKey)) {
            //取时间戳
            String reqTime = DateUtils.getNextDayStr(0, DateUtils.YYYYMMDDHHMMSS_PATTERN);
            // custNo + reqTime + key
            String authCode = custNo + reqTime + authCodeKey;
            // 进行MD5加密
            authCode = MD5Util.getMD5(authCode, Charsets.UTF_8.toString());
            // 替换参数
            return url.replace("$custNo$", custNo).replace("$promotionUser$", empNo).replace("$sourceShopCode$", storeCode).replace("$reqTime$", reqTime).replace("$authCode$", authCode);
        }
        return "";
    }

    /**
     * 查询是否绑定易付宝账户
     */
    @Override
    public AccountActiveQueryResp isActive(String custNo) {
        AccountActiveQueryResp resp = null;
        // 组装查询请求信息
        AccountActiveQueryReq req = new AccountActiveQueryReq("queryEPPAccountActiveStatus", "SNEG", "md5", "", "utf-8",
                custNo);
        try {
            // 调用esb接口服务
            MbfResponse response = esbService.queryAccountActiveStatus(req);
            // 确定返回信息不为空
            if (response != null && response.getOutput() != null) {
                resp = new AccountActiveQueryResp();
                // 转换成XML格式
                Document doc = XmlUtils.getW3CDom(response.toString());
                // EPPMBR_ERR003:参数错误, EPPMBR_ERR801:未绑定易付宝账号
                String status = XmlUtils.getValueByXpath(doc, "/MbfService/output1/MbfHeader/ServiceResponse/Status");
                String errCode = XmlUtils.getValueByXpath(doc, "/MbfService/output1/MbfHeader/ServiceResponse/Code");
                if ("COMPLETE".equals(status)) {
                    resp.setBinding(true);
                    // 取激活标志位
                    String flag = XmlUtils.getValueByXpath(doc, "/MbfService/output1/flag");
                    // 0：未激活；1：已激活
                    resp.setActive( "1".equals(flag) ? true : false);
                    return resp;
                } else if ("FAIL".equals(status) && "EPPMBR_ERR801".equals(errCode)) {
                    resp.setBinding(false);
                    return resp;
                }
            }
        } catch (Exception e) {
            LOGGER.error("isActive esb Error, custNo:" + custNo, e);
        }
        return null;
    }

}
